package com.myapp.core;

// * (0), / (1), + (2), - (3)
public class TreeNode {
	private boolean isOperation;
	private int value;
	private TreeNode leftChild, rightChild, parrent;
	public boolean visited;

	public TreeNode(int value, boolean op) {
		this.value = value;
	}

	public TreeNode(TreeNode node) {
		this.isOperation = node.isOperation;
		this.value = node.value;
		this.leftChild = node.leftChild;
		this.rightChild = node.rightChild;
		this.parrent = node.parrent;
	}

	public void switchContext(TreeNode node) {
		TreeNode copy = new TreeNode(this);

		this.isOperation = node.isOperation;
		this.value = node.value;
		this.leftChild = node.leftChild;
		this.rightChild = node.rightChild;
		this.parrent = node.parrent;

		node.isOperation = copy.isOperation;
		node.value = copy.value;
		node.leftChild = copy.leftChild;
		node.rightChild = copy.rightChild;
		node.parrent = copy.parrent;
	}

	public boolean selfEvaluate() {
		if (isOperation) {
			if (leftChild != null && rightChild != null
					&& !leftChild.isOperation && !rightChild.isOperation) {
				int result = 0;
				int leftValue = leftChild.getValue();
				int rightValue = rightChild.getValue();

				switch (value) {
				case 0: {// multiply
					result = leftValue * rightValue;
				}
				case 1: {// divide
					result = leftValue / rightValue;
				}
				case 2: {// sum
					result = leftValue + rightValue;
				}
				case 3: {// subtract
					result = leftValue - rightValue;
				}
				}

				isOperation = false;
				leftChild = null;
				rightChild = null;
				value = result;
				return true;
			}
		}

		return false;
	}

	public boolean hasLeft() {
		return leftChild != null;
	}

	public boolean hasRight() {
		return rightChild != null;
	}

	public boolean isOperation() {
		return isOperation;
	}

	public void setOperation(boolean isOperation) {
		this.isOperation = isOperation;
	}

	public int getValue() {
		return value;
	}

	public void setValue(int value) {
		this.value = value;
	}

	public TreeNode getLeftChild() {
		return leftChild;
	}

	public void setLeftChild(TreeNode leftChild) {
		leftChild.setParrent(this);
		this.leftChild = leftChild;
	}

	public TreeNode getRightChild() {
		return rightChild;
	}

	public void setRightChild(TreeNode rightChild) {
		rightChild.setParrent(this);
		this.rightChild = rightChild;
	}

	public TreeNode getParrent() {
		return parrent;
	}

	public void setParrent(TreeNode parrent) {
		this.parrent = parrent;
	}
}